package wec_wallet.ebo.com.activity.capital;

import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import bassproject.ebo.com.ebobass.activity.MyBaseActivity;
import bassproject.ebo.com.ebobass.http_utils.interfaces.IHttpPostListener;
import bassproject.ebo.com.ebobass.utils.IToast;
import bassproject.ebo.com.ebobass.utils.I_Share;
import bassproject.ebo.com.ebobass.utils.JsonT;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import wec_wallet.ebo.com.R;
import wec_wallet.ebo.com.bean.Coin;
import wec_wallet.ebo.com.common.Constants;
import wec_wallet.ebo.com.util.NoDoubleClickListener;
import wec_wallet.ebo.com.utils.Functions;
import wec_wallet.ebo.com.utils.URLs;
import wec_wallet.ebo.com.widget.CoinSpinnerPop;

/**
 * 转入
 */
public class ChangeIntoActivity extends MyBaseActivity {
    @BindView(R.id.changeinto_code)
    ImageView changeintoCode;
    @BindView(R.id.changeinto_num)
    TextView changeintoNum;
    @BindView(R.id.txtvwSpinner)
    TextView txtvwSpinner;
    @BindView(R.id.changeinto_copy)
    Button changeintoCopy;
    CoinSpinnerPop coinSpinnerPop;
    ArrayList<Coin> list = new ArrayList<>();
    String coinname;
    private Bitmap qrcode;

    Drawable drawable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_into);
        ButterKnife.bind(this);
        findViewById(R.id.actionbar_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        coinname = getIntent().getStringExtra(Constants.WALLETID);
        getSubjectList();

        coinSpinnerPop = new CoinSpinnerPop(this, list);
        coinSpinnerPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                drawable = getResources().getDrawable(R.drawable.arrow_down);  //(API 21以上才能使用此方法)
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                txtvwSpinner.setCompoundDrawables(null, null, drawable, null);
            }
        });
        coinSpinnerPop.setOnItemClick(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (list.size()<1)
                    return;
                coinname = list.get(i).getWallet_id();
                getChangeInto(list.get(i));
                coinSpinnerPop.dismiss();
            }
        });

        changeintoCopy.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (TextUtils.isEmpty(changeintoNum.getText().toString())) {

                } else {
                    ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                    // 将文本内容放到系统剪贴板里。
                    cm.setText(changeintoNum.getText().toString());
                    IToast.show(getResources().getString(R.string.copy_success));
                }
            }
        });
    }

    private void getSubjectList() {
        if (I_Share.isLogin()) {
            Map<String, Object> postParams = new HashMap<String, Object>();
            postParams.put("token", I_Share.readAccountToken());
            postParams.put("uid", I_Share.readAccountUserid());
            Functions.post(this, URLs.TRANSFERINTO, postParams, new IHttpPostListener() {
                @Override
                public void onTimeOut() {

                }
                @Override
                public void responseSuccess(String result) {
                    try {
                        if (!TextUtils.isEmpty(result)) {
                            JsonT<ArrayList<Coin>> json = JSON.parseObject(result, new TypeReference<JsonT<ArrayList<Coin>>>() {
                            });
                            if (json.getIs_auth() != null && json.getIs_auth() == 0) {
                                Functions.relogin(ChangeIntoActivity.this);
                                return;
                            }
                            ArrayList<Coin> data = json.getData();
                            list.clear();
                            list.addAll(data);
                            if (data != null) {
                                if (json.getData().size() > 0) {
                                    if (TextUtils.isEmpty(coinname)){
                                        coinname = json.getData().get(0).getWallet_id();
                                        getChangeInto(list.get(0));
                                    }else {
                                        for (int i = 0;i<list.size();i++){
                                            if (list.get(i).getWallet_id().equals(coinname)){
                                                getChangeInto(list.get(i));
                                                break;
                                            }
                                        }
                                    }



                                }
                            }

                        }
                    } catch (Exception e) {
                        IToast.show(getResources().getString(R.string.data_error));
                    }
                }
            }, true, false);
        } else {
            finish();
        }
    }

    private void getChangeInto(Coin coin) {
        qrcode = generateQRCode(coin.getAddress_url());
        if (qrcode != null && !qrcode.equals("")) {
            changeintoCode.setImageBitmap(qrcode);
        }
        changeintoNum.setText(coin.getAddress_url());
        txtvwSpinner.setText(coin.getWallet_name());
    }

    @Override
    public void initViews() {


    }

    @Override
    public void onClick(View v) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (qrcode != null)
            qrcode = null;

    }

    private Bitmap generateQRCode(String content) {
        try {
            QRCodeWriter writer = new QRCodeWriter();
            // MultiFormatWriter writer = new MultiFormatWriter();
            BitMatrix matrix = writer.encode(content, BarcodeFormat.QR_CODE, 500, 500);
            return bitMatrix2Bitmap(matrix);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }

    //图片处理方法
    private Bitmap bitMatrix2Bitmap(BitMatrix matrix) {
        int w = matrix.getWidth();
        int h = matrix.getHeight();
        int[] rawData = new int[w * h];
        for (int i = 0; i < w; i++) {
            for (int j = 0; j < h; j++) {
                int color = Color.WHITE;
                if (matrix.get(i, j)) {
                    color = Color.BLACK;
                }
                rawData[i + (j * w)] = color;
            }
        }

        Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);
        bitmap.setPixels(rawData, 0, w, 0, 0, w, h);
        return bitmap;
    }

    /**
     */
    private void setArrowImage() {
        drawable = getResources().getDrawable(R.drawable.arrow_up);  //(API 21以上才能使用此方法)
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        txtvwSpinner.setCompoundDrawables(null, null, drawable, null);
    }

    @OnClick(R.id.txtvwSpinner)
    public void onViewClicked() {
        coinSpinnerPop.showPopupWindow(txtvwSpinner);
        setArrowImage();
    }
}
